/*************************************************************************
> File Name: Multi-concurrent_servers.c
> Author: hzy
> Created Time: 2023-09-20 17:09:21
> Description:多线程并发服务器
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

typedef struct ClientInformation
{
    int connfd;
    // 客户端的信息
    struct sockaddr_in client_addr;
} CIF;

void *task(void *arg)
{
    CIF client = *((CIF *)arg);

    // 转化并打印客户端信息
    printf("----------------------------------\n");
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client.client_addr.sin_addr, client_ip, sizeof(client_ip));
    printf("Connection succeeded!\n");
    printf("client->ip: %s | port: %d\n", client_ip, ntohs(client.client_addr.sin_port));

    // 接受信息
    char recv_buf[512] = "";
    int ret = 0;
    while ((ret = recv(client.connfd, recv_buf, sizeof(recv_buf), 0)) > 0)
    {
        send(client.connfd, recv_buf, sizeof(recv_buf), 0);
        bzero(recv_buf, sizeof(recv_buf));
        if (ret <= 0)
        {
            // 关闭已连接的套接字
            close(client.connfd);
            pthread_exit(NULL);
        }
    }
}

int main(int argc, char const *argv[])
{
    // 1、创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        return -1;
    }

    // 2、端口复用
    int optval = 1;
    socklen_t len = sizeof(optval);
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, len);

    // 3、设置本地信息
    struct sockaddr_in my_addr;
    bzero(&my_addr, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(10086);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    // 4、绑定信息
    int bind_ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
    if (bind_ret != 0)
    {
        perror("bind");
        close(sockfd);
        return -1;
    }

    // 5、监听
    int listen_ret = listen(sockfd, 3);
    if (listen_ret != 0)
    {
        perror("listen");
        close(sockfd);
        return -1;
    }

    // 6、等待连接
    while (1)
    {
        //创建客户端结构体的对象
        CIF *cli = (CIF *)malloc(sizeof(CIF));

        bzero(&cli->client_addr, sizeof(cli->client_addr));
        socklen_t clientaddr_len = sizeof(cli->client_addr);

        // 6.1、等待连接的到来
        cli->connfd = accept(sockfd, (struct sockaddr *)&cli->client_addr, &clientaddr_len);
        if (cli->connfd < 0)
        {
            perror("accept");
            continue;
        }

        // 创建线程处理服务
        pthread_t tid;
        pthread_create(&tid, NULL, task, cli);
        // 实现线程分离
        pthread_detach(tid);
    }

    close(sockfd);
    return 0;
}